package com.neusoft.elm.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.neusoft.elm.dao.BusinessDao;
import com.neusoft.elm.dao.CartDao;
import com.neusoft.elm.dao.DeliveryAddressDao;
import com.neusoft.elm.dao.OrderDetailetDao;
import com.neusoft.elm.dao.OrdersDao;
import com.neusoft.elm.dao.impl.BusinessDaoImpl;
import com.neusoft.elm.dao.impl.CartDaoImpl;
import com.neusoft.elm.dao.impl.DeliveryAddressDaoImpl;
import com.neusoft.elm.dao.impl.OrderDetailetDaoImpl;
import com.neusoft.elm.dao.impl.OrdersDaoImpl;
import com.neusoft.elm.po.Business;
import com.neusoft.elm.po.Cart;
import com.neusoft.elm.po.DeliveryAddress;
import com.neusoft.elm.po.OrderDetailet;
import com.neusoft.elm.po.Orders;
import com.neusoft.elm.service.OrdersService;
import com.neusoft.elm.util.DBUtil;

/**
 * 订单服务实现类
 */
public class OrdersServiceImpl implements OrdersService {
    
    // 新订单流程：查询当前用户购物车中当前商家的所有食品，然后生成订单和订单详细，最后返回订单号
    @Override
    public int createOrders(String userId, Integer businessId, Integer daId) {
        int orderId = 0;
        BusinessDao businessDao = new BusinessDaoImpl();
        CartDao cartDao = new CartDaoImpl();
        OrdersDao ordersDao = new OrdersDaoImpl();
        OrderDetailetDao orderDetailetDao = new OrderDetailetDaoImpl();
        DeliveryAddressDao deliveryAddressDao = new DeliveryAddressDaoImpl();
        try {
            System.out.println("开始创建订单 - 用户ID: " + userId + ", 商家ID: " + businessId + ", 地址ID: " + daId);
            DBUtil.beginTransaction();
            
            // 1. 查询当前用户购物车中当前商家的所有食品
            Cart cart = new Cart();
            cart.setBusinessId(businessId);
            cart.setUserId(userId);
            List<Cart> cartList = cartDao.listCart(cart);
            System.out.println("购物车商品数量: " + cartList.size());
            
            if (cartList.isEmpty()) {
                System.out.println("购物车为空，无法创建订单");
                return 0;
            }
            
            // 2. 查询商家信息，需要使用商家的配送费信息
            Business business = businessDao.getBusinessById(businessId);
            System.out.println("商家信息: " + business.getBusinessName() + ", 配送费: " + business.getDeliveryPrice());
            
            // 查询配送地址信息，用于保存地址快照
            DeliveryAddress deliveryAddress = deliveryAddressDao.getDeliveryAddressById(daId);
            System.out.println("配送地址: " + (deliveryAddress != null ? deliveryAddress.getAddress() : "地址不存在"));
            
            // 3. 计算订单总额
            Double ordersTotal = 0.0;  // 订单总额
            for (Cart c : cartList) {
                // 累计所有食品总价格
                Double itemTotal = c.getFood().getFoodPrice() * c.getQuantity();
                ordersTotal += itemTotal;
                System.out.println("商品: " + c.getFood().getFoodName() + " x " + c.getQuantity() + " = " + itemTotal);
            }
            // 加上配送费
            ordersTotal += business.getDeliveryPrice();
            System.out.println("订单总额: " + ordersTotal);
            
            // 3. 创建订单，获取订单号（包含配送地址快照信息）
            Orders orders = new Orders();
            orders.setUserId(userId);
            orders.setBusinessId(businessId);
            orders.setOrderTotal(ordersTotal);
            orders.setDaId(daId);
            
            // 保存下单时的配送地址快照信息，确保后续地址修改不影响历史订单
            if (deliveryAddress != null) {
                orders.setContactName(deliveryAddress.getContactName());
                orders.setContactSex(deliveryAddress.getContactSex());
                orders.setContactTel(deliveryAddress.getContactTel());
                orders.setAddress(deliveryAddress.getAddress());
            }
            
            orderId = ordersDao.saveOrders(orders);
            System.out.println("创建订单成功，订单ID: " + orderId);
            
            // 4. 根据购物车数据，创建订单详细（包含商品快照信息）
            List<OrderDetailet> orderDetailetList = new ArrayList<>();  // 订单详细列表
            for (Cart c : cartList) {
                OrderDetailet od = new OrderDetailet();
                od.setOrderId(orderId);
                od.setFoodId(c.getFoodId());
                od.setQuantity(c.getQuantity());
                
                // 保存下单时的商品快照信息，确保后续商品信息修改不影响历史订单
                if (c.getFood() != null) {
                    od.setFoodName(c.getFood().getFoodName());
                    od.setFoodPrice(c.getFood().getFoodPrice());
                    od.setFoodExplain(c.getFood().getFoodExplain());
                }
                
                orderDetailetList.add(od);
            }
            System.out.println("准备插入 " + orderDetailetList.size() + " 条订单明细");
            
            // 5. 批量添加订单详细
            int detailResult = orderDetailetDao.saveOrderDetailetBatch(orderDetailetList);
            System.out.println("订单明细插入结果: " + detailResult);
            
            // 6. 清空当前用户购物车中当前商家的所有食品
            int cartResult = cartDao.removeCart(cart);
            System.out.println("清空购物车结果: " + cartResult);
            
            DBUtil.commitTransaction();
            System.out.println("订单创建成功，事务已提交");
        } catch (Exception e) {
            orderId = 0;
            System.out.println("创建订单失败: " + e.getMessage());
            try {
                DBUtil.rollbackTransaction();
                System.out.println("事务已回滚");
            } catch (Exception e1) {
                System.out.println("事务回滚失败: " + e1.getMessage());
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close(); // 关闭Connection
        }
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        Orders orders = null;
        OrdersDao ordersDao = new OrdersDaoImpl();
        OrderDetailetDao orderDetailetDao = new OrderDetailetDaoImpl();
        try {
            System.out.println("开始获取订单详情，订单ID: " + orderId);
            DBUtil.getConnection();
            orders = ordersDao.getOrdersById(orderId);
            if (orders != null) {
                // 为订单设置订单明细信息
                List<OrderDetailet> orderDetailetList = orderDetailetDao.listOrderDetailetByOrderId(orders.getOrderId());
                orders.setList(orderDetailetList);
                System.out.println("订单详情获取成功，商家: " + orders.getBusiness().getBusinessName() + ", 明细数量: " + orderDetailetList.size());
            } else {
                System.out.println("订单不存在，订单ID: " + orderId);
            }
        } catch (Exception e) {
            System.out.println("获取订单详情失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        List<Orders> list = new ArrayList<>();
        OrdersDao ordersDao = new OrdersDaoImpl();
        OrderDetailetDao orderDetailetDao = new OrderDetailetDaoImpl();
        try {
            DBUtil.getConnection();
            list = ordersDao.listOrdersByUserId(userId);
            // 为每个订单设置订单详细信息
            for (Orders orders : list) {
                List<OrderDetailet> orderDetailetList = orderDetailetDao.listOrderDetailetByOrderId(orders.getOrderId());
                orders.setList(orderDetailetList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public List<Orders> listOrdersByBusinessId(Integer businessId) {
        List<Orders> list = new ArrayList<>();
        OrdersDao ordersDao = new OrdersDaoImpl();
        OrderDetailetDao orderDetailetDao = new OrderDetailetDaoImpl();
        try {
            System.out.println("开始获取商家订单列表，商家ID: " + businessId);
            DBUtil.getConnection();
            list = ordersDao.listOrdersByBusinessId(businessId);
            System.out.println("获取到 " + list.size() + " 个订单");
            // 为每个订单设置订单详细信息
            for (Orders orders : list) {
                List<OrderDetailet> orderDetailetList = orderDetailetDao.listOrderDetailetByOrderId(orders.getOrderId());
                orders.setList(orderDetailetList);
            }
        } catch (Exception e) {
            System.out.println("获取商家订单列表失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public int updateOrderState(Integer orderId, Integer orderState) {
        int result = 0;
        OrdersDao dao = new OrdersDaoImpl();
        try {
            System.out.println("开始更新订单状态 - 订单ID: " + orderId + ", 新状态: " + orderState);
            DBUtil.getConnection();
            result = dao.updateOrderState(orderId, orderState);
            System.out.println("订单状态更新完成 - 结果: " + result);
        } catch (Exception e) {
            System.out.println("订单状态更新失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return result;
    }
}